/*+***********************************************************************************
 Filename: 02_mic_dac01\src\dac_pt8211.v
 Description: a module convert audio data to serial format which connects dac pt8211-s chip.

 Modification:
   2024.02.29 Creation   H.Zheng

Copyright (C) 2024  Zheng Hui (hzheng@gzhu.edu.cn)

License: MulanPSL-2.0

***********************************************************************************-*/

module dac_pt8211(
	input wire data_in_clk,
	input wire [15:0] data_r,
	input wire [15:0] data_l,
	input wire dac_if_bck,
	output wire dac_if_ws,
	output wire dac_if_data
);

  //posedge of data_in_clk latch in audio data from data_r and data_l

  reg [15:0] data_r_buffer, data_l_buffer;

  always @(posedge data_in_clk) begin
    data_r_buffer <= data_r;
    data_l_buffer <= data_l;
  end

  //shift register to hold and shift the frame data
  reg [31:0] shift_reg;

  //a 5bit counter to control the frame format
  reg [4:0] bck_counter;

  always @(negedge dac_if_bck) begin
    bck_counter <= bck_counter + 1'b1;

    if (bck_counter == 5'b11111) begin
      shift_reg <= {data_l_buffer, data_r_buffer};  //load data
    end else begin
      shift_reg <= {shift_reg[30:0], 1'b0};  //shift data
    end 
  end

  //negative edge of bck trigger bck_counter change, and then trigger ws change.
  assign dac_if_ws = (bck_counter <16) ? 1'b1 : 1'b0;

  //parellel to serial
  assign dac_if_data = shift_reg[31];




endmodule